<template>
  <div v-show="hasContent" class="map-tootip map-tootip-right" v-loading="loading" :class="{ 'map-tootip-right-show': rightShow }">
    <div class="bg"></div>
    <span class="arrow-btn" @click="rightShow = !rightShow">
      <i :class="rightShow ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"></i>
    </span>
    <div class="content">
      <div>
        <span>当前选择：</span>
        <el-select v-model="checkFeature.SMID" @change="handleFeatureChange">
          <el-option :label="`${item.properties.FEATURENAME} - ${item.properties.NAME || item.properties.CODE}`" v-for="item in checkFeatureDatas" :key="item.properties.SMID" :value="item.properties.SMID"></el-option>
        </el-select>
      </div>
      <div class="tab-pane">
        <dynamic-form v-if="hasContent" ref="dynamicForm" :fields="fields" :initial-data="formData" :confirm-before-save="confirmBeforeSave" @field-change="handleFieldChange" />
        <div v-else class="empty-tip">
          暂无属性数据
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
import { sessionStorage } from '@/deps/utils'
import { getPorperyGridApi, updatePropertyApi } from '@/deps/api'
let featureData = null
export default {
  props: {
    confirmBeforeSave: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rightShow: true,
      fields: [],
      formData: {},
      originalData: {},
      hasContent: false,
      loading: false,
      featureSids: {},
      checkFeature: {},
      checkFeatureDatas: []
    }
  },
  created() {
    this.$bus.$on('CHANGE_LAYER_INFO', this.handleLayerInfoChange)
  },
  beforeDestroy() {
    featureData = null
    this.$bus.$off('CHANGE_LAYER_INFO', this.handleLayerInfoChange)
  },
  computed: {
    nowFeature() {
      return this.checkFeatureDatas.find(item => item.properties.SMID === this.checkFeature.SMID)
    }
  },
  methods: {
    clearAll() {
      this.featureSids = {}
      this.checkFeature = {}
      this.checkFeatureDatas = []
      this.hasContent = false
      this.fields = []
      this.formData = {}
      this.loading = false
    },
    hideOrRemove(f) {
      const index = this.checkFeatureDatas.findIndex(item => item.properties.SMID === f.SMID)
      console.error(index)
      if (index >= 0) {
        this.$bus.$emit('CLEAR_HIGH_BY_RIGHT', f.SMID)
        this.checkFeatureDatas.splice(index, 1)
        delete this.featureSids[f.SMID]
      }
      if (!this.checkFeatureDatas.length) {
        this.hasContent = false
        this.fields = []
        this.formData = {}
        this.loading = false
        return
      }
      if (this.checkFeature.SMID === f.SMID) {
        this.checkFeature = this.checkFeatureDatas[0].properties
        this.handleFeatureChange()
      }
    },
    handleFeatureChange() {
      this.queryFormData(cloneDeep(this.nowFeature))
    },
    searchDataFun() {
      if (this.featureSids[f.properties.SMID]) {
        this.checkFeature = cloneDeep(f.properties)
      } else {
        this.checkFeatureDatas.push(cloneDeep(f))
      }
      this.queryFormData(cloneDeep(f))
    },
    handleLayerInfoChange(f) {
      if (f.fromSearch) {
        this.searchDataFun(f)
        return
      }
      if (this.featureSids[f.properties.SMID]) {
        this.hideOrRemove(f.properties)
        return
      } else {
        this.checkFeature = cloneDeep(f.properties)
        this.featureSids[this.checkFeature.SMID] = this.checkFeature.SMID
        this.checkFeatureDatas.push(cloneDeep(f))
      }
      this.queryFormData(cloneDeep(f))
    },
    queryFormData(f) {
      this.loading = true // 开始加载
      this.$bus.$emit('CHANGE_LAYER_INFO_BY_RIGHT_SELECT', f)
      const queryData = {
        rootid: f.properties.C_SYS_ROOT_ID,
        smid: f.properties.SMID,
        tablename: f.properties.LAYERNAME
      }
      console.error(f, 11111111111)
      getPorperyGridApi(queryData)
        .then(res => {
          this.fields = Array.isArray(res) ? res : []
          this.formData = this.extractFormData(f.properties)
          this.originalData = JSON.parse(JSON.stringify(this.formData))
          this.hasContent = this.fields.length > 0
          this.loading = false
          if (this.hasContent) {
            this.rightShow = true
          }
        })
        .catch(() => {
          this.hasContent = false
          this.fields = []
          this.formData = {}
          this.loading = false
        })
    },
    extractFormData(properties) {
      const data = {}
      this.fields.forEach(field => {
        if (field && field.tag) {
          data[field.tag] = properties[field.tag] || field.value || ''
        }
      })
      return data
    },
    handleFieldChange({ field, value, originalValue, confirm, showtype }) {
      if (value === originalValue) return
      console.error(this.formData, field, value, originalValue, confirm)
      const saveAction = () => {
        const userData = sessionStorage('userData')
        const data = {
          userName: userData.userName,
          rootid: featureData.properties.C_SYS_ROOT_ID,
          smid: featureData.properties.SMID,
          tablename: featureData.properties.LAYERNAME,
          fieldvalue: `${field}:,:${value}:,:${showtype}:;:`
        }
        console.error(data)
        updatePropertyApi(data)
          .then(res => {
            if (res.success) {
              this.$message.success('保存成功')
              this.originalData[field] = value
            } else {
              this.$message.error(res.message || '保存失败')
              this.formData[field] = originalValue
            }
          })
          .catch(error => {
            this.$message.error('保存失败: ' + error.message)
            this.formData[field] = originalValue
          })
      }

      if (confirm) {
        this.$confirm('是否保存修改?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(saveAction)
          .catch(() => {
            this.formData[field] = originalValue
          })
      } else {
        saveAction()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.map-tootip-right {
  .content {
    display: flex;
    flex-direction: column;
    height: 100%;

    .title-tab {
      display: flex;
      .tab-btn {
        padding: 8px 16px 16px;
        font-size: 16px;
      }
    }

    .tab-pane {
      flex: 1;
      overflow: auto;
      padding: 0 10px;

      .empty-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: var(--text-color);
        font-size: 14px;
      }
    }
  }
}
</style>
